go to previous page   go to home page   go to next page

Answer:

sliderA = new JSlider( JSlider.HORIZONTAL, 0, 1000, 400);
sliderB = new JSlider( JSlider.HORIZONTAL, 0, 1000, 400);
 . . . 
sliderA.setName( "sliderA" ); 
sliderB.setName( "sliderB" ); 

sliderA.addChangeListener( this ); 
sliderB.addChangeListener( this ); 

Any two unique strings will work. It is OK to use the same word for the reference variable and the name of a component. The two are completely separate, and Java will not get confused.


The getSource() Method

An event object contains a reference to the component that generated the event. To extract that reference from the event object use:

Object getSource()

Since the return type of getSource() is Object (the class at the very top of the class hierarchy) use a type cast with it:

// listener method
public void stateChanged( ChangeEvent evt )
{
  JSlider source;

  source = (JSlider)evt.getSource();
  . . . .
}

Now you have a reference to the slider that caused the event and you can use any of that slider's methods.


QUESTION 10:

(Review:) What interface does a slider's listener implement?